#include <mosquitto.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "mqtt_client_core.h"
#include "mqtt_client_publish.h"
#include "mqtt_client_subscribe.h"


/* single mode */
MqttClientCore* MqttClientCore::MqttClient = nullptr;

MqttClientCore* MqttClientCore::GetInterface() {
    if (!MqttClient) {
        static GC* clear = new GC();
        MqttClient = new MqttClientCore();
    }
        
    return MqttClient;
}

MqttClientCore::MqttClientCore()
    :MqttSub(new MqttClientSubscribe())
{

}

MqttClientCore::~MqttClientCore() {

}

MqttClientCore::MosquittoHandl 
MqttClientCore::create_mosquitto() {
    struct mosquitto *mosq;
	int rc;

	/* Required before calling other mosquitto functions */
	mosquitto_lib_init();

	/* Create a new client instance.
	 * id = NULL -> ask the broker to generate a client id for us
	 * clean session = true -> the broker should remove old sessions when we connect
	 * obj = NULL -> we aren't passing any of our private data for callbacks
	 */
	mosq = mosquitto_new(NULL, true, NULL);
	if(mosq == NULL){
		fprintf(stderr, "Error: Out of memory.\n");
	}

    return mosq;
}

/* Publish and subscribe */
void MqttClientCore::mqtt_cleint_publish(const char* topic, const char* message) {

    this->MqttPub->mqtt_cleint_publish(topic, message);
}

short MqttClientCore::mqtt_client_subscribe(const char* topic) {
    return this->MqttSub->mqtt_client_subscribe(topic);
}